<?php

namespace Restaurant\Controller;


use Core\Constant;
use Core\Controller\RestaurantAdminBaseController;
use Core\Exception\BusinessException;
use Core\Helper\CommonHelper;
use Core\Helper\HtmlPurifierHelper;
use Core\Session\FrontSessionHelper;
use Exception;
use Logger;
use Zend\View\Model\JsonModel;


class ArticleController extends RestaurantAdminBaseController {
    public function indexAction() {
        $this->initPageWithLayout();

        $categoryTable = $this->getResTableFinder()->getCategoryTable(
            FrontSessionHelper::getCurrentLang());
        $allMainArticleGroup = $categoryTable->getAllCategoriesByGroupCode(
            Constant::$CATEGORY_GROUP_ARTICLE);
        unset($allMainArticleGroup[0]);
        $this->getViewModel()->setVariable('allMainArticleGroup', $allMainArticleGroup);

        $allSubArticleGroup = $categoryTable->getAllCategoriesByGroupCode(
            Constant::$CATEGORY_GROUP_SUBARTICLE);
        unset($allSubArticleGroup[0]);
        $this->getViewModel()->setVariable('allSubArticleGroup', $allSubArticleGroup);

        return $this->getViewModel();
    }

    public function listAction()
    {
        try{
            $categoryId = $this->params()->fromPost("category");
            $subCategoryId = $this->params()->fromPost("subCategory");
            $name = $this->params()->fromPost("name");

            $searchOption = array();
            $searchOption['categoryId'] = $categoryId;
            $searchOption['subCategoryId'] = $subCategoryId;
            $searchOption['header'] = $name;

            $sortData = $this->params()->fromPost("sort");
            if($sortData){
                $order = array();
                foreach ($sortData as $sortField) {
                    $field = $sortField['field'];
                    $direction = $sortField['dir'];
                    if($field == 'order_number'){
                        if($direction == 'asc')
                            $direction = 'desc';
                        else
                            $direction = 'asc';
                    }
                    $orderClause = $field." ".$direction;
                    array_push($order, $orderClause);
                }
            }else{
                $order = array("order_number desc");
            }

            $page = $this->params()->fromPost("page");
            $rows = $this->params()->fromPost("pageSize");
            $offset = ($page - 1) * $rows;

            $articleTable = $this->getResTableFinder()->getArticleTable($this->domainCode);
            $result = $articleTable->searchArticle(true, $offset, $rows, $order, $searchOption);

            return new JsonModel(array(
                'rows' => $result['rows'],
                'total' => $result['total'],
                'success'=>true,
            ));

        }catch(Exception $e){
            $this->fireExceptionEvent($e, \Core\Constant::$EVENT_NAME_DISTRIBUTION_EXCEPTION);
            return $this->genJsonErrorView($e);
        }

    }

    public function addAction() {
        $this->initPageWithLayout();
        $categoryTable = $this->getResTableFinder()->getCategoryTable(
            FrontSessionHelper::getCurrentLang());
        $allMainArticleGroup = $categoryTable->getAllCategoriesByGroupCode(
            Constant::$CATEGORY_GROUP_ARTICLE);
        unset($allMainArticleGroup[0]);
        $this->getViewModel()->setVariable('allMainArticleGroup', $allMainArticleGroup);

        $allSubArticleGroup = $categoryTable->getAllCategoriesByGroupCode(
            Constant::$CATEGORY_GROUP_SUBARTICLE);
        unset($allSubArticleGroup[0]);
        $this->getViewModel()->setVariable('allSubArticleGroup', $allSubArticleGroup);

        $id =  $this->params()->fromQuery('id');
        $articleTable = $this->getResTableFinder()->getArticleTable();
        $articleItem = $articleTable->getArticle($id);
        $this->getViewModel()->setVariable('articleItem', $articleItem);

        return $this->getViewModel();
    }



    public function saveAction()
    {
        try{

            $domain = strtolower($this->domainCode);
            $id = $this->params()->fromPost('id');
            $name =  HtmlPurifierHelper::purifyDefault($this->params()->fromPost('name'));
            $description = $this->params()->fromPost('description');
            $content =  HtmlPurifierHelper::purifyDefault($this->params()->fromPost('content'));
            $thumbImage = $this->params()->fromPost('thumbImage');
            $categoryArr = $this->params()->fromPost('categories');
            $subcategoryArr = $this->params()->fromPost('subcategories');
            $active = $this->params()->fromPost('active');

            $description = HtmlPurifierHelper::purifyDefault($description);
            $alias = strtolower(CommonHelper::vietnameseToASCII($name));
            $articleTable = $this->getResTableFinder()->getArticleTable($domain);

            $article = $articleTable->getArticleByAlias($alias);
            if($article)
                throw new BusinessException('Đã tồn tại bài viết có tên: '.$name);

            $transactionProxy = $this->getTableGatewayTransactionProxy();
            $transactionProxy->setAbstractTable($articleTable);

            if($id){
                $transactionProxy->updateArticle(array('id'=>$id,"header"=>$name, 'sumarize'=>$description,
                    "thumbnail"=>$thumbImage,"alias"=>$alias,
                    "categories"=>$categoryArr,"subCategories"=>$subcategoryArr,
                    "content"=>$content, "active"=>$active));
            }else{
                $transactionProxy->addArticle(array("header"=>$name, 'sumarize'=>$description,
                    "thumbnail"=>$thumbImage,"alias"=>$alias,
                    "categories"=>$categoryArr,"subCategories"=>$subcategoryArr,
                    "content"=>$content, "active"=>$active));
            }

            return new JsonModel(array(
                'success'=>true,
            ));

        }catch(Exception $e){
            $this->fireExceptionEvent($e, \Core\Constant::$EVENT_NAME_DISTRIBUTION_EXCEPTION);
            return $this->genJsonErrorView($e);
        }

    }


    public function activeAction()
    {
        try{
            $domain = strtolower($this->domainCode);
            $id = $this->params()->fromPost('id');

            $articleTable = $this->getResTableFinder()->getArticleTable($domain);

            $articleTable->toggleActiveOfArticle($id);

            return new JsonModel(array(
                'success'=>true,
            ));

        }catch(Exception $e){
            $this->fireExceptionEvent($e, \Core\Constant::$EVENT_NAME_DISTRIBUTION_EXCEPTION);
            return $this->genJsonErrorView($e);
        }

    }

    public function doUpAction()
    {
        try{
            $domain = strtolower($this->domainCode);
            $id = $this->params()->fromPost('id');

            $articleTable = $this->getResTableFinder()->getArticleTable($domain);

            $articleTable->upArticle($id);

            return new JsonModel(array(
                'success'=>true,
            ));

        }catch(Exception $e){
            $this->fireExceptionEvent($e, \Core\Constant::$EVENT_NAME_DISTRIBUTION_EXCEPTION);
            return $this->genJsonErrorView($e);
        }

    }

    public function doDownAction()
    {
        try{
            $domain = strtolower($this->domainCode);
            $id = $this->params()->fromPost('id');

            $articleTable = $this->getResTableFinder()->getArticleTable($domain);

            $articleTable->downArticle($id);

            return new JsonModel(array(
                'success'=>true,
            ));

        }catch(Exception $e){
            $this->fireExceptionEvent($e, \Core\Constant::$EVENT_NAME_DISTRIBUTION_EXCEPTION);
            return $this->genJsonErrorView($e);
        }

    }

    public function deleteAction()
    {
        try{
            $domain = strtolower($this->domainCode);
            $id = $this->params()->fromQuery('id');

            $articleTable = $this->getResTableFinder()->getArticleTable($domain);

            $transactionProxy = $this->getTableGatewayTransactionProxy();
            $transactionProxy->setAbstractTable($articleTable);

            $transactionProxy->doDelete($id);

            return new JsonModel(array(
                'success'=>true,
            ));

        }catch(Exception $e){
            $this->fireExceptionEvent($e, \Core\Constant::$EVENT_NAME_DISTRIBUTION_EXCEPTION);
            return $this->genJsonErrorView($e);
        }

    }
}